import Tab from '@/components/Tab';
import {useLayoutEffect, useRef, useState} from 'react';
import {ScrollView, View} from 'react-native';
import PagerView from 'react-native-pager-view';
import {useTranslation} from 'react-i18next';
import {useHeaderHeight} from '@react-navigation/elements';
import Statistics from '@/pages/scene/Owner/statistics';
import {DeviceItem} from '@/pages/scene/Owner/device';
import StationSummary from '@/pages/OwnerMain/summary/StationSummary';
import {Button, Card, Icon, Search, Text, useAppTheme} from 'tsun-smart-ui';
import {DeviceStatus} from '@/enums/devices';
import PageContent, {PageTemplate} from '@/components/PageContent';
import {deviceApi} from '@/services/api/deviceApi';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {StationAlarmModel, stationApi} from '@/services/api/stationApi';
import {TotalMap} from '@/pages/scene/Owner/device';
const StationInfo = ({
  navigation,
  route: {
    params: {id, stationName},
  },
}: ReactNavigation.RootStackScreenProps<'StationInfo'>) => {
  useLayoutEffect(() => {
    navigation.setOptions({
      title: stationName,
    });
  }, []);
  const [activeTab, setActiveTab] = useState('overview');
  const {t} = useTranslation();
  const theme = useAppTheme();
  const headerHeight = useHeaderHeight();
  const [searchText, setSearchText] = useState('');
  const [showSearch, setShowSearch] = useState(false);
  const {top} = useSafeAreaInsets();
  const [activeDeviceTab, setActiveDeviceTab] = useState<
    keyof typeof DeviceStatus | undefined
  >();
  const tabs = [
    {
      key: 'overview',
      title: t('workplace.docs.Overview'),
    },
    {
      key: 'statistics',
      title: t('pb.statistics'),
    },
    {
      key: 'device',
      title: t('device.equipment'),
    },
    {
      key: 'alarm',
      title: t('user.alarm'),
    },
  ];
  const filterTabs = [
    {
      id: void 0,
      title: t('monitor.chat.options.all'),
    },
    {
      id: 'normal',
      title: t('job.status.Normal'),
    },
    {
      id: 'offline',
      title: t('monitor.tab.title.offline'),
    },
    {
      id: 'alarm',
      title: t('user.alarm'),
    },
  ] as const;
  const pagerViewRef = useRef<PagerView>(null);
  const AlarmItem = ({item}: {item: StationAlarmModel}) => {
    return (
      <Card>
        <Text variant="bodyStrong" className="mb-2">
          {item.message}
        </Text>
        <View className=" gap-x-[2]">
          <Text
            style={{
              color: theme.colors?.neutral?.primary,
            }}>
            SN:{item.deviceSn}
          </Text>
          <Text
            style={{
              color: theme.colors?.neutral?.primary,
            }}>
            {t('device.name')}:{item.deviceName}
          </Text>
          <Text
            style={{
              color: theme.colors?.neutral?.primary,
            }}>
            {t('sys.app.time')}:{item.ct}
          </Text>
        </View>
      </Card>
    );
  };
  return (
    <View style={{paddingTop: headerHeight}} className="flex-1">
      <Tab
        tabs={tabs}
        size="small"
        className="mt-3 mb-1"
        activeKey={activeTab}
        onChange={(key, index) => {
          setActiveTab(key);
          pagerViewRef.current?.setPage(index);
        }}
      />
      <PagerView
        className="flex-1 relative"
        onLayout={() => {
          pagerViewRef.current?.setScrollEnabled(false);
        }}
        onPageSelected={e => {
          setActiveTab(tabs[e.nativeEvent.position].key);
        }}
        ref={pagerViewRef}>
        <View key="overview" style={{marginTop: -top - 36}}>
          <StationSummary
            // @ts-ignore
            station={{
              id: +id,
            }}
            showGradient={false}></StationSummary>
        </View>
        <View key="statistics" className="pb-4">
          <Statistics stationId={+id}></Statistics>
        </View>
        <View key="device" className="pb-4 px-4">
          <PageContent
            renderItem={DeviceItem}
            api={deviceApi.getStationEquipment}
            params={{
              deviceStatus: activeDeviceTab,
              deviceName: searchText,
              deviceSn: searchText,
              stationId: +id,
            }}>
            <PageTemplate.default>
              {({dispatch, total, setTotal, setHasMore, restData}) => {
                return (
                  <View
                    key={'device'}
                    className="flex-row  mt-[10px] mb-3 rounded-lg w-full items-center"
                    style={{
                      backgroundColor: theme.colors?.neutral?.white,
                    }}>
                    {showSearch ? (
                      <Search
                        className="flex-1 pr-5"
                        placeholder={t('common.search')}
                        autoFocus
                        value={searchText}
                        onChangeText={setSearchText}
                        onBlur={() => {
                          setShowSearch(false);
                        }}
                        cancelText={t('user.logOutCancel', {
                          defaultValue: '取消',
                        })}
                        onSubmitEditing={() => {
                          dispatch({
                            type: 'setPageNum',
                            payload: 1,
                          });
                          setShowSearch(false);
                        }}></Search>
                    ) : (
                      <View className="px-5 flex-1 flex-row items-center">
                        <ScrollView
                          showsHorizontalScrollIndicator={false}
                          contentContainerClassName="gap-x-6"
                          horizontal>
                          {filterTabs.map((tab, i) => (
                            <View key={tab.title}>
                              <Button
                                size="large"
                                variant="text"
                                title={`${tab.title}${`(${
                                  restData?.statusCount?.[
                                    TotalMap[tab.id] ?? 'total'
                                  ] ?? '0'
                                })`}`}
                                textStyle={{
                                  color:
                                    activeDeviceTab === tab.id
                                      ? theme.colors?.brand?.primary
                                      : theme.colors?.neutral?.primary,
                                }}
                                onPress={() => {
                                  setTotal(undefined);
                                  dispatch({
                                    type: 'setPageNum',
                                    payload: 1,
                                  });
                                  setHasMore(true);
                                  setActiveDeviceTab(tab.id!);
                                }}></Button>
                            </View>
                          ))}
                        </ScrollView>
                        <Icon
                          name="search"
                          size={20}
                          onPress={() => {
                            setShowSearch(true);
                          }}
                          className="ml-10"
                          color={theme.colors?.neutral?.primary}></Icon>
                      </View>
                    )}
                  </View>
                );
              }}
            </PageTemplate.default>
          </PageContent>
        </View>
        <View key="alarm" className="pb-4 px-4 mt-[10]">
          <PageContent
            renderItem={AlarmItem}
            params={{
              stationId: +id,
            }}
            api={stationApi.getStationAlarmList}></PageContent>
        </View>
      </PagerView>
    </View>
  );
};

export default StationInfo;
